// wordbook-list.js
const getBuiltinBooks = require('../../../utils/builtinBooks').getBuiltinBooks;
const cloudConfig = require('../../../utils/cloudConfig');
const storageManager = require('../../../manager/storageManager').getInstance();

Page({
  data: {
    wordbooks: [], // 原始词书数据
    filteredWordbooks: [], // 过滤后的词书数据
    versionTabs: ['全部'], // 版本Tab列表
    activeTab: '全部', // 当前激活的Tab
    searchKeyword: '', // 搜索关键词
    loading: false, // 加载状态
    BOOK_COVERS_PATH_PREFIX: cloudConfig.BOOK_COVERS_PATH_PREFIX, // 书籍封面URL前缀
    selectedBookIds: [] // 已选择的词书ID列表
  },

  onLoad: function() {
    // 加载词书数据
    this.loadWordbooks();
  },

  /**
   * 加载词书数据
   */
  async loadWordbooks() {
    this.setData({ loading: true });
    
    try {
      // 获取词书数据
      const books = await getBuiltinBooks();
      
      // 提取所有版本
      const versions = this.extractVersions(books);
      
      // 获取已选择的词书列表
      const selectedBookIds = this.getSelectedBookIds();
      
      this.setData({
        wordbooks: books,
        versionTabs: ['全部', ...versions, '其他'],
        selectedBookIds: selectedBookIds,
        loading: false
      });
      
      // 初始化过滤列表
      this.filterWordbooks();
    } catch (error) {
      console.error('加载词书数据失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 获取已选择的词书ID列表
   */
  getSelectedBookIds() {
    const wordBooks = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_BOOKS) || [];
    return wordBooks.map(book => book.id);
  },

  /**
   * 提取所有唯一的版本信息
   */
  extractVersions(books) {
    const versionSet = new Set();
    
    books.forEach(book => {
      if (book.version) {
        versionSet.add(book.version);
      }
    });
    
    // 转换为数组并排序
    return Array.from(versionSet).sort();
  },

  /**
   * 切换版本Tab
   */
  switchVersionTab(e) {
    const version = e.currentTarget.dataset.version;
    
    this.setData({
      activeTab: version
    }, () => {
      // 切换后重新过滤词书
      this.filterWordbooks();
    });
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  /**
   * 搜索确认
   */
  onSearchConfirm() {
    this.filterWordbooks();
  },

  /**
   * 清空搜索
   */
  onClearSearch() {
    this.setData({
      searchKeyword: ''
    }, () => {
      this.filterWordbooks();
    });
  },

  /**
   * 过滤词书列表
   */
  filterWordbooks() {
    const { wordbooks, activeTab, searchKeyword, selectedBookIds } = this.data;
    
    let filtered = wordbooks;
    
    // 按版本过滤
    if (activeTab !== '全部') {
      if (activeTab === '其他') {
        filtered = filtered.filter(book => !book.version);
      } else {
        filtered = filtered.filter(book => book.version === activeTab);
      }
    }
    
    // 按关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(book => 
        book.name.toLowerCase().includes(keyword) ||
        (book.grade && book.grade.toLowerCase().includes(keyword))
      );
    }
    
    // 为每个词书添加是否已选择的标识
    filtered = filtered.map(book => ({
      ...book,
      isSelected: selectedBookIds.includes(book.id)
    }));
    
    this.setData({
      filteredWordbooks: filtered
    });
  },

  /**
   * 根据学段获取词书图标
   */
  getBookIcon(schoolStage) {
    switch (schoolStage) {
      case '小学':
        return '🏫';
      case '初中':
        return '📝';
      case '高中':
        return '🎓';
      default:
        return '📚';
    }
  },

  /**
   * 选择词书
   */
  selectWordbook(e) {
    const { id, name } = e.currentTarget.dataset;
    const app = getApp();
    const wordDataManager = app.globalData.wordDataManager;
    
    // 检查词书是否已存在
    const existingBooks = wordDataManager.getAllBooks();
    const existingBook = existingBooks.find(b => b.id === id);
    
    if (existingBook) {
      // 如果词书已存在，直接返回上一页并刷新数据
      wx.showToast({ title: '词书已存在', icon: 'none' });
    } else {
      // 导入词书的逻辑（从原wb-bottom-actions.js的onSelectBuiltinBook和importBuiltinBook合并）
      this.importBuiltinBook(id, name).then(() => {
        // 导入成功后返回上一页
        wx.navigateBack({
          delta: 1,
          complete: () => {
            setTimeout(() => {
              // 通知上一页刷新数据
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 1];
              if (prevPage && prevPage.onRefresh) {
                prevPage.onRefresh();
              }
            }, 500);
          }
        });
      });
    }
  },

  /**
   * 导入内置词书
   */
  async importBuiltinBook(bookId, bookName) {
    wx.showLoading({ title: '导入词书...' });
    try {
      const app = getApp();
      const wordDataManager = app.globalData.wordDataManager;
      const cloudManager = app.globalData.cloudManager || app.getCloudManager();
      
      // 从云开发环境下载对应的json文件
      const { WORD_BOOKS_PATH_PREFIX } = require('../../../utils/cloudConfig');
      const fileID = `${WORD_BOOKS_PATH_PREFIX}${bookId}.json`;
      
      // 下载文件
      console.log('开始下载词书文件:', fileID);
      const downloadRes = await cloudManager.downloadFile(fileID);
      
      // 读取文件内容
      const fileContent = await new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
          filePath: downloadRes.tempFilePath,
          encoding: 'utf-8',
          success: res => resolve(res.data),
          fail: err => reject(err)
        });
      });
      
      // 解析JSON文件内容
      const jsonContent = JSON.parse(fileContent);
      
      // 准备词书数据
      const book = {
        id: bookId,
        name: bookName,
        wordCount: jsonContent.wordCount || 0,
        schoolStage: jsonContent.schoolStage || '',
        version: jsonContent.version || '',
        grade: jsonContent.grade || '',
        semester: jsonContent.semester || ''
      };
      
      // 使用解析的JSON内容处理单词
      const lines = jsonContent.content.split('\n');
      const wordIds = [];
      
      // 解析每一行单词
      lines.forEach((line, index) => {
        const lineNumber = index + 1;
        if (line.trim()) {
          const parts = line.trim().split(/\t+/);
          if (parts.length >= 2) {
            const english = parts[0];
            const chinese = parts[1];
            // 为每个group元素添加 ${bookId}- 前缀
            const groups = parts.length > 2 ? parts[2].split(';').map(group => `${bookId}-${group}`) : [];
            const categories = parts.length > 3 ? parts[3].split(';') : [];
            
            // 检查单词是否已存在
            const words = wordDataManager.getAllWords();
            let wordId = Object.keys(words).find(id => 
              words[id].english.toLowerCase() === english.toLowerCase() && 
              words[id].chinese === chinese
            );
            
            // 如果不存在则创建新单词
            if (!wordId) {
              wordId = wordDataManager.addWord({
                english,
                chinese,
                categories,
                groups,
                bookTranslations: {}
              });
            } else {
              // 如果存在则更新分类、分组
              const currentCategories = words[wordId].categories || [];
              const currentGroups = words[wordId].groups || [];
              const newCategories = [...new Set([...currentCategories, ...categories])];
              const newGroups = [...new Set([...currentGroups, ...groups])];
              
              wordDataManager.updateWord(wordId, {
                categories: newCategories.length > 0 ? newCategories : undefined,
                groups: newGroups.length > 0 ? newGroups : undefined
              });
            }
            
            wordIds.push(wordId);
          }
        }
      });
      
      // 创建或更新词书
      const existingBooks = wordDataManager.getAllBooks();
      const existingBook = existingBooks.find(b => b.id === bookId);
      
      if (existingBook) {
        // 更新现有词书，确保wordIds没有重复
        const uniqueWordIds = [...new Set(wordIds)];
        wordDataManager.updateBook(existingBook.id, { 
          wordIds: uniqueWordIds, 
          updateTime: new Date().toISOString()
        });
      } else {
        // 创建新词书，确保wordIds没有重复
        const uniqueWordIds = [...new Set(wordIds)];
        wordDataManager.addBook({
          ...book,
          type: 'textbook',
          wordIds: uniqueWordIds
        });
      }
      
      wx.showToast({ title: '词书导入成功', icon: 'success' });
    } catch (e) {
      console.error('导入内置词书失败', e);
      wx.showToast({ title: '词书导入失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  }
});